// components/calendar/calendar.js
var app = getApp();

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    // 开始、结束时间
    startDate: {
      value: '',
      type: String
    },
    endDate: {
      value: '',
      type: String
    },
    showTime: {
      type: String
    },

    // 日历是否展示
    calendarModal: {
      value: false,
      type: Boolean
    },

  },
  // 组件监听
  observers: {

    // 日历显示与否
    'calendarModal': function (calenda) {
      // console.log(calenda);
      this.setData({
        visible: calenda
      })
      this.tode()
    },
    // 开始、结束
    'startDate,endDate': function (star, end) {
      console.log(star, end);
      this.setData({
        _starDate: star,
        _endDate: end
      })
    },
  },
  /**
   * 组件的初始数据
   */
  data: {
    currentTimestamp: '',
    nowTimestamp: '', //当前时间戳
    currentDate: "", //当前选择年月
    dayList: '',
    currentDayList: '',
    currentObj: '', //当前时间戳
    nowObj: '', //目前时间戳
    currentDay: '',
    nowData: '',
    currentYear: '',
    nowYear: '',
    nowMonth: '',
    select: [],
    countDates: '',
    monthVisible: false,
    //日期初始化选中样式
    _starDate: '',
    _endDate: ''
  },

  /**
   * 组件的方法列表
   */
  created() {

  },



  methods: {
    tode: function () {
      var that = this;
      // 获取当前时间
      var currentObj = this.getCurrentDayString()
      let moth = (currentObj.getMonth() + 1).toString().padStart(2, '0')
      var now = new Date();
      // console.log(now);
      this.setData({
        currentDate: currentObj.getFullYear() + '-' + moth,
        currentObj: currentObj,
        currentTimestamp: currentObj.getTime(),
        /*  获取当前的年、月、日  */
        currentYear: currentObj.getFullYear(),
        currentDay: currentObj.getDate(),
        currentMonth: (currentObj.getMonth() + 1),
        nowTimestamp: now.getTime(),
        nowData: currentObj.getDate(),
        nowYear: currentObj.getFullYear(),
        nowMonth: (currentObj.getMonth() + 1),
        nowObj: currentObj,
      })
      // console.log(this.data.nowTimestamp);
      this.setSchedule(currentObj);

    },
    onColumnChange(e) {
      // console.log('pick', e.detail.value);

      var dateTime = new Date(e.detail.value);
      // console.log(dateTime);
      this.setData({
        currentDate: e.detail.value,
        currentObj: dateTime,
        // 获取时间戳（单位：毫秒）
        currentTimestamp: dateTime.getTime(),
        /*  获取当前的年、月  */
        currentYear: dateTime.getFullYear(),
        currentMonth: (dateTime.getMonth() + 1),
      })
      // console.log("选择当前：" + this.data.currentObj);
      // console.log('currentYear' + this.data.currentDate);
      this.setSchedule(dateTime);

    },
    mothSelect() {
      this.setData({
        monthVisible: true
      })
    },
    onVisibleChange(e) {
      this.setData({
        visible: e.detail.visible,
        calendarModal: e.detail.visible
      });
    },
    // 时间戳转换日期
    transformTime: function (dat) {
      // console.log(date);
      let date = new Date(dat)
      const year = date.getFullYear(); // 获取年份
      const month = date.getMonth() + 1; // 获取月份（注意月份是从0开始的，需要加1）
      const day = date.getDate(); // 获取日期
      const formattedDay = day.toString().padStart(2, '0'); // 日期补零
      const formattedYear = year.toString().padStart(2, '0'); // 年份补零
      const formattedMonth = month.toString().padStart(2, '0'); // 月份补零
      return `${formattedYear}-${formattedMonth}-${formattedDay}`; //2023-1-1 0:0:0格式
    },
    doDay: function (e) {
      // console.log(e.currentTarget.dataset);
      var that = this;
      var currentObj = that.data.currentObj
      var Y = currentObj.getFullYear();
      var m = currentObj.getMonth() + 1;
      var d = currentObj.getDate();
      var str = ''
      if (e.currentTarget.dataset.key == 'left') {
        m -= 1
        if (m <= 0) {
          str = (Y - 1) + '/' + 12 + '/' + d
        } else {
          str = Y + '/' + m + '/' + d
        }
      } else {
        m += 1
        if (m <= 12) {
          str = Y + '/' + m + '/' + d
        } else {
          str = (Y + 1) + '/' + 1 + '/' + d
        }
      }
      currentObj = new Date(str)
      // console.log(str);
      // console.log('currentObj ' + currentObj);
      // + currentObj.getDate()
      // console.log(currentObj.getMonth());
      let moth = (currentObj.getMonth() + 1).toString().padStart(2, '0')

      this.setData({
        currentDate: currentObj.getFullYear() + '-' + moth,
        currentObj: currentObj,
        currentTimestamp: currentObj.getTime(),
        /*  获取当前的年、月  */
        currentYear: currentObj.getFullYear(),
        currentMonth: (currentObj.getMonth() + 1),
      })
      // console.log("选择当前：" + that.data.currentObj);
      // console.log('currentYear' + that.data.currentDate);


      this.setSchedule(currentObj);
    },
    getCurrentDayString: function () {
      var objDate = this.data.currentObj
      if (objDate != '') {
        return objDate
      } else {
        var c_obj = new Date()
        var a = c_obj.getFullYear() + '/' + (c_obj.getMonth() + 1) + '/' + c_obj.getDate()
        return new Date(a)
      }
    },
    setSchedule: function (currentObj) {
      var that = this
      var m = currentObj.getMonth() + 1
      var Y = currentObj.getFullYear()
      var d = currentObj.getDate();

      var currentDayNum = new Date(Y, m, 0).getDate()
      var currentDayWeek = currentObj.getUTCDay() + 1
      var result = currentDayWeek - (d % 7 - 1);
      var firstKey = result <= 0 ? 7 + result : result;
      var currentDayList = [];

      var f = 0
      for (var i = 0; i < 42; i++) {
        let list = {
          day: '',
          timeStamp: ''
        };
        if (i < firstKey - 1) {
          list.day = ''
          list.timeStamp = ''
        } else {
          if (f < currentDayNum) {
            list.day = f + 1;
            f = list.day
            let da = new Date(Y, currentObj.getMonth(), f);
            // 将日期转换为时间戳（单位为毫秒）
            list.timeStamp = da.getTime();
          } else if (f >= currentDayNum) {
            list.day = ''
            list.timeStamp = ''
          }
        }
        currentDayList[i] = list
      }
      // console.log(currentDayList);
      that.setData({
        currentDayList: currentDayList
      })
    },
    // 确定传值
    getData() {
      let starDate = this.data._starDate
      let endDate = this.data._endDate
      let show = this.data._starDate + '至' + this.data._endDate
      this.triggerEvent('customEvent', {starDate,endDate});
      this.setData({
        calendarModal: false,
        startDate:this.data._starDate,
        endDate:this.data._endDate
        // _starDate: '',
        // _endDate: '',
        // currentMonth: '',
        // nowData: '',
        // currentYear: '',
        // select: [],
      })
    },
    //选择具体日期方法--xzz1211
    selectDay: function (e) {
      var that = this;

      var starDate = '',
        endDate = '',
        that = this,
        countDate = ''
      var select = this.data.select
      var obj = {}
      obj.year = this.data.currentYear
      obj.month = this.data.currentMonth
      obj.date = e.target.dataset.day
      obj.timeStamp = new Date(this.data.currentYear, (this.data.currentMonth - 1), e.target.dataset.day).getTime()
      if (select.length < 2) {
        select.push(obj)
        starDate = select[0].year + '-' + select[0].month.toString().padStart(2, '0') + '-' + select[0].date.toString().padStart(2, '0')
        if (select.length == 2) {

          endDate = select[1].year + '-' + select[1].month.toString().padStart(2, '0') + '-' + select[1].date.toString().padStart(2, '0')

          if (select[0].timeStamp > select[1].timeStamp) {
            // console.log('第一个时间大于第二个时间')
            select = []
            select.push(obj)
            starDate = select[0].year + '-' + select[0].month.toString().padStart(2, '0') + '-' + select[0].date.toString().padStart(2, '0')
            endDate = ''

          } else {
            endDate = select[1].year + '-' + select[1].month.toString().padStart(2, '0') + '-' + select[1].date.toString().padStart(2, '0')
            starDate = select[0].year + '-' + select[0].month.toString().padStart(2, '0') + '-' + select[0].date.toString().padStart(2, '0')
            countDate = this.getDaysBetween(select[0].year + '-' + select[0].month + '-' + select[0].date, that.data.currentYear + '-' + select[1].month + '-' + select[1].date)
          }
        }
      } else {
        // console.log('第三个')
        select = []
        select.push(obj)
        // console.log(select);
        starDate = select[0].year + '-' + select[0].month.toString().padStart(2, '0') + '-' + select[0].date.toString().padStart(2, '0')
      }
      // console.log(select, starDate, endDate, 88888, countDate)
      that.setData({
        currentDay: e.target.dataset.day, //选择的数据，非真实当前日期
        currentDa: e.target.dataset.day, //选择某月具体的一天
        // currentDate: that.data.currentYear + '-' + (that.data.currentMonth + 1).toString().padStart(2, '0'),
        currentYear: that.data.currentYear,
        currentMonth: that.data.currentMonth,
        _endDate: endDate,
        _starDate: starDate,
        select: select,
        countDates: countDate
      })
      // console.log(select);

      // + e.target.dataset.day,//真实选择数据
      // console.log("当前选择日期：" + that.data.currentDate);
    },
    getDaysBetween: function (dateString1, dateString2) {
      var startDate = Date.parse(dateString1);
      var endDate = Date.parse(dateString2);
      if (startDate > endDate) {
        return 0;
      }
      if (startDate == endDate) {
        return 1;
      }
      var days = parseInt((endDate - startDate) / (1 * 24 * 60 * 60 * 1000));
      return days;
    },

  }
})